//
//  BIPageControl.m
//  PageControl
//
//  Created by Zhenglinqin on 15/5/28.
//  Copyright (c) 2015年 Binglin. All rights reserved.
//

#import "BIPageControl.h"


@interface BIPageControl ()
{
    NSMutableArray *_pageItems;
}

@end


@implementation BIPageControl

#pragma mark - init
- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self initialize];
    }
    return self;
}


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self initialize];
    }
    return self;
}

- (void)initialize{
    _pageItems = [NSMutableArray new];
    _selectPage = 0;
    _indicatorWidth = 10.0f;
    _hideForSingle  = YES;

    _indicatorSpace = 2.0f;
    _selectColor = [UIColor lightGrayColor];
    _normalColor = [UIColor whiteColor];
    _pageNumber = 0;

    self.backgroundColor = [UIColor clearColor];
}

#pragma mark - property override
- (void)setPageNumber:(NSInteger)pageNumber{
    if (_pageNumber != pageNumber) {
        _pageNumber = pageNumber;
        [_pageItems removeAllObjects];
        
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        if (self.hideForSingle && _pageNumber <= 1) {
            return;
        }
        for (int i = 0; i < self.pageNumber; i ++) {
            CGRect frame = [self frameForItem:i];
            frame.size = CGSizeMake(self.indicatorWidth, self.indicatorWidth);
            frame.origin.y =  self.frame.size.height - self.indicatorWidth;
            UIView *item = [[UIImageView alloc] initWithFrame:frame];
            [_pageItems addObject:item];
            [self addSubview:item];
            
        }
    }
    [self setNeedsDisplay];
}

- (void)setSelectPage:(NSInteger)selectPage{

    if (self.pageNumber == 0) {
        return;
    }

    
    if (_selectPage == selectPage) {
        return;
    }

    _selectPage = selectPage;
    [self setNeedsDisplay];

}

- (void)setSelectColor:(UIColor *)selectColor{
    _selectColor = selectColor;
    [self setNeedsDisplay];
}

- (void)setNormalColor:(UIColor *)normalColor{
    _normalColor = normalColor;
    [self setNeedsDisplay];
}

- (void)setSelectImage:(UIImage *)selectImage{
    _selectImage = selectImage;
    [self setNeedsDisplay];
}


#pragma mark - dotView

- (void)resetForLayerAtIndex:(NSInteger)index select:(BOOL)select{
    
    UIImageView *viewItem = _pageItems[index];
    viewItem.frame = [self frameForItem:index];
    viewItem.backgroundColor = [UIColor blackColor];
    
    if (select) {
        if (self.selectImage) {
            viewItem.image = self.selectImage;
            viewItem.backgroundColor = [UIColor clearColor];
        }else{
            viewItem.image = nil;
            viewItem.backgroundColor = self.selectColor;
        }
    }else{
        if (self.normalImage) {
            viewItem.image = self.normalImage;
            viewItem.backgroundColor = [UIColor clearColor];
        }else{
            viewItem.image = nil;
            viewItem.backgroundColor = self.normalColor;
        }
    }
    
    viewItem.layer.cornerRadius = viewItem.frame.size.width/2.0;
    
    UIColor *strokeColor = select ? self.strokeColor_select : self.strokeColor_normal;
    viewItem.layer.borderColor = strokeColor ? strokeColor.CGColor : viewItem.backgroundColor.CGColor;
    viewItem.layer.borderWidth = 1;

}



#pragma mark - size
- (CGSize)instrictSize{
    return
    ({CGSize size;
        size.width = self.edgeInsets.left + self.edgeInsets.right +
                     self.indicatorSpace * (self.pageNumber - 1)
                     + self.pageNumber * self.indicatorWidth;
        size.height = self.edgeInsets.top + self.edgeInsets.bottom + self.indicatorWidth;
        size;
    });
}

- (void)sizeToFit{
    self.frame = ({CGRect frame = self.frame; frame.size = [self instrictSize]; frame;});
}


- (CGSize)sizeForItem:(NSInteger)i{
    if (i == self.selectPage && self.selectImage) {
        return self.selectImage.size;
    }
    return CGSizeMake(self.indicatorWidth, self.indicatorWidth);
}

- (CGRect)frameForItem:(NSInteger)index{
    
    CGRect frame =
    ({
        CGRect itemFrame = CGRectZero;
        CGFloat originX  = 0;
        itemFrame.size = [self sizeForItem:index];
        itemFrame.origin.y = (self.frame.size.height - itemFrame.size.height)/2.0;

        if (self.alignMode == BIPageControlAlignModeBottomCenter) {
            originX =  (self.frame.size.width - self.instrictSize.width)/2.0;
        }else if (self.alignMode == BIPageControlAlignModeBottomLeft){
            originX = self.edgeInsets.left;
        }else if (self.alignMode == BIPageControlAlignModeBottomRight){
            originX = self.frame.size.width - self.instrictSize.width + self.edgeInsets.left;
        }
        
        itemFrame.origin.x = originX + index * self.indicatorWidth + self.indicatorWidth/ 2.0 - itemFrame.size.width/2.0 + self.indicatorSpace * index;
        itemFrame;
    });
    return frame;
}

- (UIImageView *)viewAtIndex:(NSInteger)index{
    return _pageItems[index];
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    if (self.hideForSingle && _pageNumber <= 1) {
        return;
    }

    for (int i = 0; i < self.pageNumber; i ++) {
        [self resetForLayerAtIndex:i select:i == _selectPage];
    }
}


@end


@interface iProgressPageControl ()

@property (nonatomic, strong) UIView  * sliderView;

@end

@implementation iProgressPageControl

- (void)setPageNumber:(NSInteger)pageNumber{
    [super setPageNumber:pageNumber];
    
    if (self.pageNumber <= 1) {
        if (self.hideForSingle) {
            self.sliderView.hidden = true;
        }
    }else{
        self.sliderView.hidden = false;
        self.progress = self.progress;
        [self addSubview:_sliderView];
    }
}

- (void)updateSliderView:(UIView *)slideView{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.sliderView = slideView;
        [self addSubview:slideView];
        self.progress = self.progress;
    });
}

- (void)setProgress:(CGFloat)progress{
    if (progress > 1.0f) {
        progress = 1.f;
    }else if (progress < 0.f){
        progress = 0.f;
    }
    _progress = progress;
    
    CGFloat currentProgress = _progress * self.pageNumber;
    CGFloat calculateAlpha  = fmod(currentProgress, 1.0);
    
    NSInteger left = (currentProgress - calculateAlpha);
    
    if (left >= 0 && left < self.pageNumber) {
        UIView *leftView = [self viewAtIndex:left];
        leftView.alpha = calculateAlpha;
    }

    NSInteger right = ceil(currentProgress);
    
    if (right >= 0 && right < self.pageNumber) {
        UIView *rightView = [self viewAtIndex:right];
        rightView.alpha = 1 - calculateAlpha;
    }
    
    [self updateSliderFrame];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self updateSliderFrame];
}

- (void)updateSliderFrame{
    
    CGFloat originX = 0;
    
    if (self.alignMode == BIPageControlAlignModeBottomCenter) {
        originX = (self.frame.size.width - self.instrictSize.width - self.edgeInsets.left - self.edgeInsets.right)/2.0;
    }else if (self.alignMode == BIPageControlAlignModeBottomLeft){
        originX = self.edgeInsets.left;
    }else if (self.alignMode == BIPageControlAlignModeBottomRight){
        originX = self.frame.size.width - self.instrictSize.width - self.edgeInsets.right;
    }
    
    originX += self.indicatorWidth / 2.0;
    
    if (originX + self.sliderView.frame.size.width / 2.0 > self.frame.size.width - self.edgeInsets.right) {
        originX = self.frame.size.width - self.edgeInsets.right;
    }
    
    CGPoint destCenter = CGPointMake(originX + (self.instrictSize.width + self.indicatorSpace)  * _progress, self.frame.size.height/2.0);
    CGFloat maxX = self.frame.size.width - self.edgeInsets.right - self.sliderView.frame.size.width/2.0;
    if (destCenter.x > maxX) {
        destCenter.x = maxX;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.sliderView.center = destCenter;
    });
}


@end